package com.payment.util;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * 网络工具类。
 *
 * @author carver.gu
 * @since 1.0, Sep 12, 2009
 */

@Component
public abstract class WebUtils {

	private static final Logger logger = LoggerFactory.getLogger(WebUtils.class);

	private static final String DEFAULT_CHARSET = "UTF-8";
	private static final String METHOD_POST = "POST";
	private static final String METHOD_GET = "GET";
	private final static String SUCC_CODE = "0000";
	private final static String RESP_CODE = "respCode";
	private final static String COMM_RESULT = "commCode";

	private static final String proxyIp = "192.68.70.122";
	private static final int proxyPort = 3128;
	private static final boolean proxyFlag = false;

	private static class DefaultTrustManager implements X509TrustManager {
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}

		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}
	}

	private WebUtils() {
	}

	/**
	 * 执行HTTP POST请求。
	 *
	 * @param url 请求地址
	 * @param params 请求参数
	 * @return 响应字符串
	 * @throws IOException
	 */
	public static String doPost(String url, Map<String, String> params, int connectTimeout, int readTimeout)
			throws IOException {
		return doPost(url, params, DEFAULT_CHARSET, connectTimeout, readTimeout);
	}

	/**
	 * 执行HTTP POST请求。
	 *
	 * @param url 请求地址
	 * @param params 请求参数
	 * @param charset 字符集，如UTF-8, GBK, GB2312
	 * @return 响应字符串
	 * @throws IOException
	 */
	public static String doPost(String url, Map<String, String> params, String charset, int connectTimeout,
			int readTimeout) throws IOException {
		String ctype = "application/x-www-form-urlencoded;charset=" + charset;
		String query = buildQuery(params, charset);
		byte[] content = {};
		if (query != null) {
			content = query.getBytes(charset);
		}
		return doPost(url, ctype, content, connectTimeout, readTimeout);
	}

	/**
	 * 执行HTTP POST请求。
	 *
	 * @param url 请求地址
	 * @param params 请求参数
	 * @param charset 字符集，如UTF-8, GBK, GB2312
	 * @return 响应字符串
	 * @throws IOException
	 */
	public static String doPost(String url, String content, String charset, int connectTimeout, int readTimeout)
			throws IOException {
		String ctype = "application/x-www-form-urlencoded;charset=" + charset;
		byte[] data = {};
		if (content != null) {
			data = content.getBytes(charset);
		}
		return doPost(url, ctype, data, connectTimeout, readTimeout);
	}

	/**
	 * 执行HTTP POST JSON请求。
	 *
	 * @param url 请求地址
	 * @param params 请求参数
	 * @param charset 字符集，如UTF-8, GBK, GB2312
	 * @return 响应字符串
	 * @throws IOException
	 */
	public static String doPostJson(String url, String json, String charset, int connectTimeout, int readTimeout)
			throws IOException {
		String ctype = "application/json;charset=" + charset;
		byte[] data = {};
		if (json != null) {
			data = json.getBytes(charset);
		}
		return doPost(url, ctype, data, connectTimeout, readTimeout);
	}

	/**
	 * 执行HTTP POST请求。
	 *
	 * @param url 请求地址
	 * @param ctype 请求类型
	 * @param content 请求字节数组
	 * @return 响应字符串
	 * @throws IOException
	 */
	private static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout)
			throws IOException {
		HttpURLConnection conn = null;
		OutputStream out = null;
		String rsp = null;
		try {
			try {
				conn = getConnection(new URL(url), METHOD_POST, ctype);
				conn.setConnectTimeout(connectTimeout);
				conn.setReadTimeout(readTimeout);
			} catch (IOException e) {
				e.printStackTrace();
				throw e;
			}
			try {
				out = conn.getOutputStream();
				out.write(content);
				rsp = getResponseAsString(conn);
			} catch (IOException e) {
				//e.printStackTrace();
				throw e;
			}

		} finally {
			if (out != null) {
				out.close();
			}
			if (conn != null) {
				conn.disconnect();
			}
		}

		return rsp;
	}

	private static HttpURLConnection getConnection(URL url, String method, String ctype) throws IOException {
		HttpURLConnection conn = null;
		if ("https".equals(url.getProtocol())) {
			SSLContext ctx = null;
			try {
				ctx = SSLContext.getInstance("TLS");
				ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
			} catch (Exception e) {
				throw new IOException(e);
			}
			HttpsURLConnection connHttps = null;
			if (proxyFlag) {
				Proxy proxy = setProxy();
				connHttps = (HttpsURLConnection) url.openConnection(proxy);
			} else {
				connHttps = (HttpsURLConnection) url.openConnection();
			}
			connHttps.setSSLSocketFactory(ctx.getSocketFactory());
			connHttps.setHostnameVerifier(new HostnameVerifier() {
				public boolean verify(String hostname, SSLSession session) {
					return false;//默认认证不通过，进行证书校验。
				}
			});
			conn = connHttps;
		} else {
			if (proxyFlag) {
				Proxy proxy = setProxy();
				conn = (HttpURLConnection) url.openConnection(proxy);
			} else {
				conn = (HttpURLConnection) url.openConnection();
			}
		}

		conn.setRequestMethod(method);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setRequestProperty("Content-Type", ctype);
		return conn;
	}

	/**
	* 设置代理
	*
	* @return
	*/
	private static Proxy setProxy() throws IOException {
		Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, proxyPort));
		System.out.println("代理 [ip：" + proxyIp + " http代理端口:" + proxyPort + " ] ");
		return proxy;
	}

	/**
	 * URLEncoder后进行key-value拼接
	 * Title: buildQuery
	 * Description:
	 * @param params
	 * @param charset
	 * @return
	 * @throws IOException
	 */
	public static String buildQuery(Map<String, String> params, String charset) throws IOException {
		if (params == null || params.isEmpty()) {
			return null;
		}

		StringBuilder query = new StringBuilder();
		Set<Entry<String, String>> entries = params.entrySet();
		boolean hasParam = false;

		for (Entry<String, String> entry : entries) {
			String name = entry.getKey();
			String value = entry.getValue();
			// 忽略参数名或参数值为空的参数
			if (StringUtils.areNotEmpty(name, value)) {
				if (hasParam) {
					query.append("&");
				} else {
					hasParam = true;
				}

				query.append(name).append("=").append(URLEncoder.encode(value, charset));
			}
		}

		return query.toString();
	}

	/**
	 * MAP转成key-value拼接
	 * Title: buildQuery
	 * Description:
	 * @param params
	 * @param charset
	 * @return
	 * @throws IOException
	 */
	public static String buildQueryParam(Map<String, String> params, String charset) throws IOException {
		if (params == null || params.isEmpty()) {
			return null;
		}

		StringBuilder query = new StringBuilder();
		Set<Entry<String, String>> entries = params.entrySet();
		boolean hasParam = false;

		for (Entry<String, String> entry : entries) {
			String name = entry.getKey();
			String value = entry.getValue();
			// 忽略参数名或参数值为空的参数
			if (StringUtils.areNotEmpty(name, value)) {
				if (hasParam) {
					query.append("&");
				} else {
					hasParam = true;
				}
				query.append(name).append("=").append(value);
			}
		}

		return query.toString();
	}

	protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
		String charset = getResponseCharset(conn.getContentType());
		InputStream es = conn.getErrorStream();
		if (es == null) {
			return getStreamAsString(conn.getInputStream(), charset);
		} else {
			String msg = getStreamAsString(es, charset);
			if (StringUtils.isEmpty(msg)) {
				throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
			} else {
				throw new IOException(msg);
			}
		}
	}

	private static String getStreamAsString(InputStream stream, String charset) throws IOException {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
			StringWriter writer = new StringWriter();

			char[] chars = new char[256];
			int count = 0;
			while ((count = reader.read(chars)) > 0) {
				writer.write(chars, 0, count);
			}

			return writer.toString();
		} finally {
			if (stream != null) {
				stream.close();
			}
		}
	}

	private static String getResponseCharset(String ctype) {
		String charset = DEFAULT_CHARSET;

		if (!StringUtils.isEmpty(ctype)) {
			String[] params = ctype.split(";");
			for (String param : params) {
				param = param.trim();
				if (param.startsWith("charset")) {
					String[] pair = param.split("=", 2);
					if (pair.length == 2) {
						if (!StringUtils.isEmpty(pair[1])) {
							charset = pair[1].trim();
						}
					}
					break;
				}
			}
		}

		return charset;
	}

	/**
	 * 执行HTTP GET请求。
	 *
	 * @param url 请求地址
	 * @param params 请求参数
	 * @return 响应字符串
	 * @throws IOException
	 */
	public static String doGet(String url, Map<String, String> params) throws IOException {
		return doGet(url, params, DEFAULT_CHARSET);
	}

	/**
	 * 执行HTTP GET请求。
	 *
	 * @param url 请求地址
	 * @param params 请求参数
	 * @param charset 字符集，如UTF-8, GBK, GB2312
	 * @return 响应字符串
	 * @throws IOException
	 */
	public static String doGet(String url, Map<String, String> params, String charset) throws IOException {
		HttpURLConnection conn = null;
		String rsp = null;

		try {
			String ctype = "application/x-www-form-urlencoded;charset=" + charset;
			String query = buildQuery(params, charset);
			try {
				conn = getConnection(buildGetUrl(url, query), METHOD_GET, ctype);
			} catch (IOException e) {
				//Map<String, String> map = getParamsFromUrl(url);
				e.printStackTrace();
				throw e;
			}

			try {
				rsp = getResponseAsString(conn);
			} catch (IOException e) {
				//Map<String, String> map = getParamsFromUrl(url);
				e.printStackTrace();
				throw e;
			}

		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}

		return rsp;
	}

	/**
	 * 执行HTTP GET请求。
	 *
	 * @param url 请求地址
	 * @param params 请求参数
	 * @param charset 字符集，如UTF-8, GBK, GB2312
	 * @return 响应字符串
	 * @throws IOException
	 */
	public static String doGet(String url, String charset) throws IOException {
		HttpURLConnection conn = null;
		String rsp = null;

		try {
			String ctype = "application/x-www-form-urlencoded;charset=" + charset;
			try {
				conn = getConnection(buildGetUrl(url, ""), METHOD_GET, ctype);
			} catch (IOException e) {
				e.printStackTrace();
				throw e;
			}

			try {
				rsp = getResponseAsString(conn);
			} catch (IOException e) {
				e.printStackTrace();
				throw e;
			}

		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
		return rsp;
	}

	/**
	 * 执行HTTP GET请求。
	 *
	 * @param url 请求地址
	 * @param params 请求参数
	 * @param charset 字符集，如UTF-8, GBK, GB2312
	 * @return 响应字符串
	 * @throws IOException
	 */
	public static HttpURLConnection getHttpUrlConnection(String url, String charset) throws IOException {
		HttpURLConnection conn = null;
		String ctype = "application/x-www-form-urlencoded;charset=" + charset;
		try {
			conn = getConnection(buildGetUrl(url, ""), METHOD_GET, ctype);
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}

		return conn;
	}

	private static URL buildGetUrl(String strUrl, String query) throws IOException {
		URL url = new URL(strUrl);
		if (StringUtils.isEmpty(query)) {
			return url;
		}

		if (StringUtils.isEmpty(url.getQuery())) {
			if (strUrl.endsWith("?")) {
				strUrl = strUrl + query;
			} else {
				strUrl = strUrl + "?" + query;
			}
		} else {
			if (strUrl.endsWith("&")) {
				strUrl = strUrl + query;
			} else {
				strUrl = strUrl + "&" + query;
			}
		}

		return new URL(strUrl);
	}

	/**
	 * 使用默认的UTF-8字符集反编码请求参数值。
	 *
	 * @param value 参数值
	 * @return 反编码后的参数值
	 */
	public static String decode(String value) {
		return decode(value, DEFAULT_CHARSET);
	}

	/**
	 * 使用默认的UTF-8字符集编码请求参数值。
	 *
	 * @param value 参数值
	 * @return 编码后的参数值
	 */
	public static String encode(String value) {
		return encode(value, DEFAULT_CHARSET);
	}

	/**
	 * 使用指定的字符集反编码请求参数值。
	 *
	 * @param value 参数值
	 * @param charset 字符集
	 * @return 反编码后的参数值
	 */
	public static String decode(String value, String charset) {
		String result = null;
		if (!StringUtils.isEmpty(value)) {
			try {
				result = URLDecoder.decode(value, charset);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		return result;
	}

	/**
	 * 使用指定的字符集编码请求参数值。
	 *
	 * @param value 参数值
	 * @param charset 字符集
	 * @return 编码后的参数值
	 */
	public static String encode(String value, String charset) {
		String result = null;
		if (!StringUtils.isEmpty(value)) {
			try {
				result = URLEncoder.encode(value, charset);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		return result;
	}

	/**
	 * 从HTTP URL中提取所有的参数。
	 *
	 * @param query URL地址
	 * @return 参数映射
	 */

	public static Map<String, Object> getParamsFromUrl(String url) {
		Map<String, Object> map = null;
		if (url != null && url.indexOf('?') != -1) {
			map = splitUrlQuery(url.substring(url.indexOf('?') + 1));
		}
		if (map == null) {
			map = new HashMap<String, Object>();
		}
		return map;
	}

	/**
	 * 从KEY-VALUE URL中提取所有的参数。
	 *
	 * @param query URL地址
	 * @return 参数映射
	 */

	public static Map<String, Object> getParamsKeyValueUrl(String url) {
		Map<String, Object> map = null;
		if (url != null) {
			map = splitUrlQuery(url);
		}
		if (map == null) {
			map = new HashMap<String, Object>();
		}
		return map;
	}

	/**
	 * 从URL中提取所有的参数。
	 *
	 * @param query URL地址
	 * @return 参数映射
	 */
	public static Map<String, Object> splitUrlQuery(String query) {
		Map<String, Object> result = new HashMap<String, Object>();

		String[] pairs = query.split("&");
		if (pairs != null && pairs.length > 0) {
			for (String pair : pairs) {
				String[] param = pair.split("=", 2);
				if (param != null && param.length == 2) {
					result.put(param[0], param[1]);
				}
			}
		}
		return result;
	}

	/**
	 * String字符串提取换行转Map
	 *
	 * @param query URL地址
	 * @return 参数映射
	 */
	public static Map<String, Object> splitUrlWrapToMap(String query) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (query == null) {
			return result;
		}
		String[] pairs = query.split("\n");
		if (pairs != null && pairs.length > 0) {
			for (String pair : pairs) {
				String[] param = pair.split("=", 2);
				if (param != null && param.length == 2) {
					result.put(param[0], param[1]);
				}
			}
		}
		return result;
	}

	//如果返回结果中有COMM_RESULT，通讯失败
	public static Map<String, Object> comm(Map<String, Object> params) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (!SignUtil.dataSign(params, "UTF-8", (String) (params.get("merId")))) {
			result.put(COMM_RESULT, "签名失败");
			return result;
		}

		String msg = JSON.toJSONString(params);

		String str = "";
		try {
			str = WebUtils.doPostJson(ConstantsUtil.getProperty("url"), msg, "UTF-8", 30000, 30000);
		} catch (Exception ex) {
			ex.printStackTrace();
			result.put(COMM_RESULT, "通讯失败");
			return result;
		}

		result = JSON.parseObject(str, HashMap.class);
		String respCode = (String) (result.get(RESP_CODE));
		// 0000 需要验签
		if (SUCC_CODE.equals(respCode)) {
			if (!SignUtil.dataVerify(result, "UTF-8")) {
				result.put(COMM_RESULT, "验签失败");
			}
		} else {
			result.remove(ConstantsUtil.getProperty("param_signature"));

		}
		logger.info("comm():" + JSON.toJSONString(result));
		return result;
	}

}
